﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SalesSys.Comm.BLL;
using SalesSys.Comm.DAL;
using SalesSys.Comm.Utility;
using SalesSys.DAL;
using SalesSys.DAL.Models;
using SalesSys.DAL;

namespace SalesSys.BLL
{
    /// <summary>
    /// 锁价单
    /// </summary>
    public class LockOrderBLL : BaseBLL<LockOrder, Guid>
    {
        /// <summary>
        /// 取消锁价单
        /// </summary>
        /// <param name="orderId"></param>
        public bool Cancel(IEmployee emp, Guid orderId)
        {
            //todo.. 验证权限
            var old = Rep.Find(orderId);
            old.State = OrderState.Cancel;
            var result = Rep.Update(old);
            return result > 0;
        }

        /// <summary>
        /// 通知财务先款审核
        /// </summary>
        /// <param name="order"></param>
        public void SendFullPayment(LockOrder order)
        {
            var old = Rep.Find(order.Id);
            order.ProcessState = ProcessState.FullPayment;
            Rep.Update(order);
        }

        /// <summary>
        /// 财务先款审核通过
        /// </summary>
        /// <param name="order"></param>
        public void ApprovalFullPayment(LockOrder order)
        {
            var old = Rep.Find(order.Id);
            old.State = OrderState.End;
            Rep.Update(order);
        }

        /// <summary>
        /// 根据关键字和状态查询锁价单
        /// </summary>
        /// <param name="searchKey">模糊查询</param>
        /// <param name="state">状态</param>
        /// <param name="qinfo">翻页属性</param>
        /// <returns></returns>
        public KeyValuePair<int, IEnumerable<LockOrder>> Select(Guid empId, string searchKey, OrderState? state, QueryInfo qinfo)
        {
            var query = Rep.Entities;
            if (!string.IsNullOrWhiteSpace(searchKey))
            {
                query = query.Where(p => p.Customer.Name.Contains(searchKey) || p.Customer.ShortName.Contains(searchKey) || p.Account.Name.Contains(searchKey));
            }
            if (state != null)
            {
                if (state.Value == OrderState.Settlement)
                    query = query.Where(p => p.IsPause == true);
                else if (state.Value == OrderState.Confirmed)
                    query = query.Where(p => p.IsApproval == true);
                else
                    query = query.Where(p => p.State == state && p.IsApproval == false && p.IsPause == false);
            }
            if (empId != null && empId != Guid.Empty)
                query = query.Where(p => p.Creater.Id == empId);
            var count = query.Count();
            var list = query.OrderByDescending(p => p.CreateTime).Paging(qinfo.Page, qinfo.Rows).ToList();
            return new KeyValuePair<int, IEnumerable<LockOrder>>(count, list);
        }

        /// <summary>
        /// 监听财务变化，支付订单
        /// </summary>
        /// <param name="account"></param>
        public static void AccountChangePayLockOrder(Account account)
        {
            FinanceBLL financeBll = new FinanceBLL();
            LockOrderBLL bll = new LockOrderBLL();
            //查询该户头下所有订单，按照顺序进行付款1、已结算\时间排序 2、查询锁价单 3、普通预付款
            var orderList = bll.GetList(p => p.Account.Id == account.Id && p.ProcessState == ProcessState.FullPayment && p.State == OrderState.Pending).OrderByDescending(p => p.CreateTime);
            foreach (var order in orderList)
            {
                //扣款
                if (financeBll.PayLockOrder(order))
                {
                    order.State = OrderState.Checked;
                    order.ProcessState = ProcessState.Checked;
                    order.IsPause = false;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]成功" });
                    //通知驻场接单
                    bll.Edit(order);
                }
            }
        }
        public static void AccountChangePayLockOrderNew(Account account, Guid empId, Guid customerId)
        {
            FinanceBLL financeBll = new FinanceBLL();
            LockOrderBLL bll = new LockOrderBLL();
            //查询该户头下所有订单，按照顺序进行付款1、已结算\时间排序 2、查询锁价单 3、普通预付款
            var orderList = bll.GetList(p => p.Account.Id == account.Id&&p.Creater.Id==empId&&p.Customer.Id==customerId && p.ProcessState == ProcessState.FullPayment && p.State == OrderState.Pending).OrderByDescending(p => p.CreateTime);
            foreach (var order in orderList)
            {
                //扣款
                if (financeBll.PayLockOrder(order))
                {
                    order.State = OrderState.Checked;
                    order.ProcessState = ProcessState.Checked;
                    order.IsPause = false;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]成功" });
                    //通知驻场接单
                    bll.Edit(order);
                }
            }
        }
        
        static LockOrderBLL()
        {
            //增加账户变化时间
            SequenceApprovalBLL.LockPriceOrderApproval.ApprovalEndHandle += LockPriceOrderApproval_ApprovalEndHandle;
            //取消
            SequenceApprovalBLL.CancelOrderApproval.ApprovalEndHandle += CancelOrderApproval_ApprovalEndHandle;
            //退款
            SequenceApprovalBLL.LockOrderRefundApproval.ApprovalEndHandle += RefundOrderApproval_ApprovalEndHandle;
        }
        /// <summary>
        /// 锁价单锁价审批流程
        /// </summary>
        /// <param name="id"></param>
        /// <param name="success"></param>
        private static void LockPriceOrderApproval_ApprovalEndHandle(Guid id, bool success, string msg)
        {
            LockOrderBLL bll = new LockOrderBLL();
            var order = bll.Details(id);
            order.IsApproval = false;
            if (success)
            {
                //提交财务先款审核
                bll.SendFullPayment(order);
                order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价审批通过" });
                FinanceBLL financeBll = new FinanceBLL();
                var paymentSuccess = financeBll.PayLockOrder(order); //扣款
                //扣款是否成功
                if (paymentSuccess)
                {
                    order.State = OrderState.Checked;
                    order.ProcessState = ProcessState.Checked;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]成功" });
                }
                else
                {
                    order.IsPause = true;
                    order.ProcessState = ProcessState.FullPayment;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]失败，余额不足。" });
                }
            }
            else
            {
                order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价审批失败" });
                bll.Cancel(null, id);
            }
            bll.Edit(order);
        }

         /// <summary>
         /// 取消锁价单回调事件
         /// </summary>
         /// <param name="id">锁价单编号</param>
         /// <param name="success">审核状态</param>
        private static void CancelOrderApproval_ApprovalEndHandle(Guid id, bool success, string msg)
         {
             LockOrderBLL bll = new LockOrderBLL();
             var order = bll.Details(id);
             order.IsApproval = false;
             if (success)
             {
                 //退款  
                 FinanceBLL financeBll = new FinanceBLL();
                 var refundSuccess = financeBll.LockOrderRefund(order, order.Total, "取消锁价单触发的退款操作");
                 if (refundSuccess)
                 {
                     order.State = OrderState.Refund;
                 }
                 else
                 {
                     bll.Cancel(null, id);//提交取消申请时已记录是谁提交的取消申请
                 }
                 order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价单[取消]操作审核结果：[成功]" });
             }
             else
             {
                 order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价单[取消]操作审核结果：[失败]" });
             }
             bll.Edit(order);
         }

         /// <summary>
         /// 退款锁价单回调事件
         /// </summary>
         /// <param name="id">锁价单编号</param>
         /// <param name="success">审核状态</param>
         /// <param name="money">金额</param>
        private static void RefundOrderApproval_ApprovalEndHandle(Guid id, bool success, decimal money, string msg)
         {
             LockOrderBLL bll = new LockOrderBLL();
             var order = bll.Details(id);
             order.IsApproval = false;
             if (success)
             {
                 //退款  
                 FinanceBLL financeBll = new FinanceBLL();
                 var refundSuccess = financeBll.LockOrderRefund(order, money, "锁价单退款触发的退款操作");
                 if (refundSuccess)
                 {
                     order.State = OrderState.Refund;
                 }
                 //else
                 //{
                 //    bll.Cancel(null, id);//提交退款申请时已记录是谁提交的退款申请
                 //}
                 order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价单[退款]操作审核结果：[成功]" });
             }
             else
             {
                 order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价单[退款]操作审核结果：[失败]" });
             }
             bll.Edit(order);
         }
    }
}
